<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\Admin\Sys;

use App\Controller\AbstractController;
use App\Middleware\AuthMiddleware;
use App\Model\ArticleTag;
use App\Model\Friend;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\DeleteMapping;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Annotation\PutMapping;

#[Middlewares([AuthMiddleware::class])]
#[Controller]
class FriendController extends AbstractController
{
    #[GetMapping(path: '/sys/friend/list')]
    public function list()
    {
        $name = $this->request->input('name', '');
        $status = $this->request->input('status', null);
        $pageNum = $this->request->input('pageNum', 1);
        $pageSize = $this->request->input('pageSize', 10);
        $where = [];
        if ($name) {
            $where[] = ['name', 'like', '%' . $name . '%'];
        }
        if (!is_null($status)) {
            $where[] = ['status', '=', $status];
        }

        $list = Friend::query()->when($where, function ($query) use ($where) {
            return $query->where($where);
        })->forPage($pageNum, $pageSize)->get();
        $data['searchCount'] = true;
        $data['current'] = (int)$pageNum;
        $data['size'] = (int)$pageSize;
        $data['total'] = Friend::query()->count();
        $data['pages'] = ceil($data['total'] / $pageSize);
        $data['records'] = $list;
        return success($data);
    }

    #[PostMapping(path: '/sys/friend/add')]
    public function add()
    {
        $params = $this->request->all();
        Friend::query()->create([
            'name' => $params['name'],
            'avatar' => $params['avatar'],
            'email' => $params['email'],
            'info' => $params['info'],
            'sort' => $params['sort'],
            'status' => $params['status'],
            'url' => $params['url']
        ]);
        return success();
    }

    #[PutMapping(path: '/sys/friend/update')]
    public function update()
    {
        $params = $this->request->all();
        Friend::query()->where('id', $params['id'])->update([
            'name' => $params['name'],
            'avatar' => $params['avatar'],
            'email' => $params['email'],
            'info' => $params['info'],
            'sort' => $params['sort'],
            'status' => $params['status'],
            'url' => $params['url']
        ]);
        return success();
    }

    #[DeleteMapping(path: '/sys/friend/delete/{ids}')]
    public function delete($ids)
    {
        $idArr = explode(',', $ids);
        Friend::query()->whereIn('id',  $idArr)->delete();
        return success();
    }
}
